package menu

import (
	"context"
	"time"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuTreeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuTreeLogic {
	return &MenuTreeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuTreeLogic) MenuTree(req *types.MenuTreeRo) (resp *types.MenuTreeRsp, err error) {
	var menus []model.MenuConfig
	if err = l.svcCtx.DB.WithContext(l.ctx).Order("Sequence ASC,ID ASC").Find(&menus).Error; err != nil {
		return nil, err
	}

	resp = new(types.MenuTreeRsp)
	for _, menu := range menus {
		menuData := types.MenuWithIdAndActions{
			MenuId: menu.ID,
			Menu: types.Menu{
				Name:     menu.Name,
				Typ:      menu.Typ,
				Memo:     menu.Name,
				ParentId: menu.ParentId,
				Status:   int(menu.Status),
				Sequence: menu.Sequence,
				Path:     menu.Path,
				Actions:  string(menu.Actions),
			},
			Actions: nil,
		}
		actionIds := menu.Actions.Unmarshal()
		for _, actionId := range actionIds {
			var action model.ActionConfig
			tx := l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", actionId).Find(&action)
			if err = tx.Error; err != nil {
				return nil, err
			}
			if tx.RowsAffected == 0 {
				continue
			}

			menuData.Actions = append(menuData.Actions, types.Action{
				ActionId:  action.ID,
				Name:      action.Name,
				Path:      action.Path,
				Method:    action.Method,
				Status:    int(action.Status),
				UpdatedAt: action.UpdatedAt.Format(time.RFC3339),
			})
		}
		resp.Items = append(resp.Items, menuData)
	}

	return
}
